package com.jessechanrui.template.shardingsphere.service.impl;

import com.jessechanrui.template.shardingsphere.entity.Employee;
import com.jessechanrui.template.shardingsphere.repository.EmployeeRepository;
import com.jessechanrui.template.shardingsphere.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl extends CrudServiceImpl<Employee, Long> implements EmployeeService {

    private EmployeeRepository employeeRepository;
    @Autowired
    public EmployeeServiceImpl(JpaRepository<Employee, Long> employeeRepository) {
        super(employeeRepository);
        this.employeeRepository = (EmployeeRepository) employeeRepository;
    }


    /**
     * the function is a transaction. If there is an exception occurred, all SQL will be rollback.
     *
     * @param employeeList
     */
    @Override
    @Transactional
    public void saveOneByOneWithTrans(List<Employee> employeeList) {
        for (int i = 0; i < employeeList.size(); i++) {
            employeeRepository.save(employeeList.get(i));
            // do something
        }
    }

    /**
     * the function is NOT a transaction. If there is an exception occurred, SQL will NOT be rollback.
     * @param employeeList
     */
    @Override
    public void saveOneByOneWithoutTrans(List<Employee> employeeList) {
        for (int i = 0; i < employeeList.size(); i++) {
            employeeRepository.save(employeeList.get(i));
            // do something
        }
    }


}
